/**
 * Created by Nie on 2015/12/10.
 */
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    $routeProvider.
    when('/company/list', {
        templateUrl: 'company/list.html',
        controller: 'companyListController'
    }).
    when('/company/edit/:code', {
        templateUrl: 'company/edit.html',
        controller: 'companyEditController'
    });
}]);

app.factory('companyService', ['$http', '$location', companyService]);
app.controller('companyListController', ['$scope', '$routeParams','$window', '$location', '$http', 'companyService', companyListController]);
app.controller('companyEditController', ['$scope','$rootScope', '$routeParams','$window', '$location', '$http', 'companyService','orderService', companyEditController]);

function companyService($http, $location) {
    return {
        //获取所有的公司（不分页）
        listAllCompanies: function (fn) {
            baas_jz.call({
                http: $http,
                method: 'get',
                uri: 'company/company/search/all/company',
                success: function (data) {
                    if (typeof fn === 'function') {
                        fn(data);
                    }
                }
            });
        },
        servantlist: function (data, limit, page, app_id, fn) {
            var param = {
                limit: limit,
                page: page,
                name: (data != '' && data != undefined) ? data.username : '',
                identify: (data != '' && data != undefined) ? data.identify : '',
                address: (data != '' && data != undefined) ? data.address : '',
                telephone: (data != '' && data != undefined) ? data.telephone : '',
                nativePlace: (data != '' && data != undefined) ? data.nativePlace : '',
                from: (data != '' && data != undefined) ? data.from : '',
                sex: (data != '' && data != undefined) ? data.sex : '',
                cers: (data != '' && data != undefined) ? data.cers : '',
                technique: (data != '' && data != undefined) ? data.technique : '',
                service: (data != '' && data != undefined) ? data.service : '',
                servantstatus: (data != '' && data != undefined) ? data.servantstatus : '',
                verifystatus: (data != '' && data != undefined) ? data.verifystatus : ''
            };
            baas_jz.call({
                'http': $http,
                'method': 'post',
                // 'uri': 'servant/servant/list',
                'uri': 'servant/servant/search',
                'data': param,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        , orderlist: function (data, limit, page, app_id, fn) {
            var param = {
                limit: limit,
                page: page,
                start_time: (data != '' && data != undefined) ? data.start_time : '',
                end_time: (data != '' && data != undefined) ? data.end_time : '',
                company: (data != '' && data != undefined) ? data.company : '',
                status: (data != '' && data != undefined) ? data.status : '',
                score: (data != '' && data != undefined) ? parseInt(data.score) : '',
                serviceType1: (data != '' && data != undefined && data.serviceType1 != undefined) ? data.serviceType1 : '',
                serviceType2: (data != '' && data != undefined && data.serviceType2 != undefined) ? data.serviceType2 : '',
                selected_manager_group_id: (data != '' && data != undefined && data.selected_manager_group_id != undefined) ? data.selected_manager_group_id : '',
                selected_company_code: (data != '' && data != undefined && data.selected_company_code != undefined) ? data.selected_company_code : '',
                //serviceType3:(data != ''&& data != undefined && data.serviceType3!=undefined)?data.serviceType3:'',
                order_id: (data != '' && data != undefined) ? data.order_id : '',
                name: (data != '' && data != undefined) ? data.username : '',
                address: (data != '' && data != undefined) ? data.address : '',
                phone: (data != '' && data != undefined) ? data.phone : ''
            };
            if (data != '' && data != undefined && data.serviceType3 != undefined)
                param.serviceType3 = data.serviceType3;
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'uri': 'order/orderList/count',
                'data': param,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }, servantList: function (data, fn) {
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'servant/servant/list',
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }

                }
            });
        }
        , ordersCount: function (group, app_id, fn) {
            var param = {
                group: group
            };
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'order/order/statistics',
                'data': param,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        , yuecount: function (start_date, company_code, app_id, fn) {
            var param = {
                year: start_date,
                selected_company_code: (typeof company_code != undefined && company_code != '') ? company_code : undefined
            };
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'order/order/year/order/count',
                'data': param,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        , moneycount: function (start_date, app_id, fn) {
            var param = {
                selected_company_code: (typeof start_date != undefined && start_date != '') ? start_date : undefined
            };
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'order/order/month/revenue/count',
                'data': param,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
        , amountCount: function (amountData, app_id, fn) {
            var param = {
                selected_manager_group_id: (typeof amountData != 'undefined' && amountData != '' && typeof amountData.selected_manager_group_id != 'undefined') ? amountData.selected_manager_group_id : '',
                selected_company_code: (typeof amountData != 'undefined' && amountData != '' && typeof amountData.selected_company_code != 'undefined') ? amountData.selected_company_code : ''
            };
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'data': param,
                'uri': 'order/orderList/total/revenue',
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },

        //Copied from uhome project by Nie
        add: function (data, app_id, recall) {
            var create = 0;
            if (arguments.length == 4 && arguments[3] == 'create') {
                create = 1;
            }
            var data = {
                name: data.name,
                code: data.code,
                faren: data.faren,
                address: data.address,
                create_time: data.create_time,
                fuzeren: data.fuzeren,
                years: data.years,
                telephone: data.telephone,
                services: data.services,
                logo: (angular.element('#J_Urls').val() != '') ? angular.element('#J_Urls').val() : data.logo,
                member_number: data.member_number,
                serviceType3_code: data.serviceType3_code,
                serviceType3_title: data.serviceType3_title,
                longitude: data.longitude,
                latitude: data.latitude,
                autoAddOrder: (data != '' && typeof data != "undefined" && typeof data.autoAddOrder != "undefined") ? data.autoAddOrder : '0'
            };
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'data': data,
                'uri': 'company/company/edit',
                'success': function (d) {
                    if (d.status == '1') {
                        if (typeof recall == 'function') {
                            recall(d);
                        }
                    } else {
                        if (d.description) {
                            alert(d.description);
                        } else {
                            alert('网络原因，请求失败，请稍后重试');
                        }
                    }
                }
            });
        },
        list: function (limit, page, app_id, fn) {
            var param = {
                limit: limit,
                page: page
            };
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'company/company/list',
                'data': param,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        find_one: function (code, app_id, fn) {
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'company/company/code/' + code,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        delete: function (code, app_id, fn) {
            var data = {
                code: code
            };
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'data': data,
                'uri': 'company/company/delete',
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        getUserType: function (fn) {
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'manager/type/list',
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        getUserGroup: function (company_code, fn) {
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'uri': 'manager/group/search/group/' + company_code,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        getUserList: function (group_id, fn) {
            var data = {
                type_code: 'companyService'
            }
            baas_jz.call({
                'http': $http,
                'method': 'get',
                'data': data,
                'uri': 'manager/manager/search/manager/' + group_id,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        saveCompanyAdmin: function (manager_id, params, fn) {
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'data': params,
                'uri': 'manager/manager/edit/' + manager_id,
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        },
        delCompanyAdmin: function (code, fn) {
            var data = {code: code};
            baas_jz.call({
                'http': $http,
                'method': 'post',
                'data': data,
                'uri': 'manager/manager/delete',
                'success': function (d) {
                    if (typeof fn == 'function') {
                        fn(d);
                    }
                }
            });
        }
    };
}

function companyEditController($scope, $rootScope, $routeParams, $window, $location, $http, companyService, orderService) {
    $scope.URL = WEB_URL;
    $scope.app_id = $routeParams.app_id;
    $scope.serviceItemList = new Array();
    $scope.manager = {};
    //上传图片
    $.getScript('../module/controller/company/kissy-company.js');


    //获得服务项目大中小类 by gxl 20150928


    $scope.serviceListNew = function () {
        var param = {};
        baas_jz.call({
            'http': $http,
            'method': 'get',
            'uri': 'console/service/map',
            'data': 'param',
            'success': function (d) {
                $scope.serviceListNew1 = d;
                if (typeof $scope.serviceListNew1 != 'undefined') {

                    for (var i = 0; i < $scope.serviceListNew1.length; i++) {
                        //console.log('test==='+$scope.serviceListNew1[i].child);
                        var list1 = $scope.serviceListNew1[i].child;
                        for (var a = 0; a < $scope.serviceListNew1[i].child.length; a++) {
                            //console.log("test===01=="+list1[a].child);
                            var list2 = $scope.serviceListNew1[i].child[a].child;
                            //console.log("test===02=="+list2);
                            for (var b = 0; b < $scope.serviceListNew1[i].child[a].child.length; b++) {
                                //console.log("test===02=="+list2[b].code);
                                if ($scope.company != undefined && $scope.company.serviceType3_code != undefined) {
                                    //console.log("test===test");
//              						console.log("test==="+$scope.serviceListNew1[i].child[a].child[b].code);
                                    for (c = 0; c < $scope.company.serviceType3_code.length; c++) {
                                        if ($scope.company.serviceType3_code[c] ==
                                            $scope.serviceListNew1[i].child[a].child[b].code) {
                                            $scope.serviceListNew1[i].child[a].child[b].chk = true;
                                            //console.log("test===test");
                                        }
                                    }

                                }
                            }
                        }

                    }


                }

            }
        });
    }


    /*end*/
    $scope.code = $routeParams.code;
    $scope.app_id = $routeParams.app_id;
    $scope.pageType = 'edit';

    $scope.getUserGroup = function () {
        angular.element('#users').show();
        companyService.getUserGroup($routeParams.code, function (d) {
            $scope.groupList = d.list;
            for (i = 0; i < d.list.length; i++) {
                var group = d.list[i];
                $scope.getUserList(group._id);
            }

        });
    }
    $scope.getUserGroup();

    $scope.userList = new Array();
    $scope.getUserList = function (group_id) {
        companyService.getUserList(group_id, function (d) {
            var u = $scope.userList;
            $scope.userList = d.list.concat($scope.userList);
        });
    }

    if ($scope.code == 0) {
        $scope.pageType = 'create';
        $scope.serviceListNew();
    }

    if ($scope.pageType == 'edit') {
        companyService.find_one($scope.code, $scope.app_id, function (json) {
            console.log(json);
            $scope.company = json;
            if (typeof $scope.company.autoAddOrder == "undefined") {
                $scope.company.autoAddOrder = 0;
            }
            $scope.serviceListNew();
        });
    }

    $scope.openEdit = function (obj, code) {
        $scope.manager = obj;
        $scope.manager_code = code;
    }
    $scope.saveCompanyService = function (obj) {
        obj.type_code = "companyService";
        obj.type_name = "企业业务员";

        if (obj.account == undefined || obj.account == "") {
            alert("请输入用户名");
            return;
        }
        if (obj.nickname == undefined || obj.nickname == "") {
            alert("请输入昵称");
            return;
        }
        if (obj.password == undefined || obj.password == "") {
            alert("请输入密码");
            return;
        }

        if (obj.group_id == undefined || obj.group_id == "") {
            alert("请选择小组");
            return;
        }
        companyService.saveCompanyAdmin($scope.manager_code, obj, function (d) {
            $scope.userList = [];
            if (d.status == 0)
                alert(d.description);
            else {
                closeMod();
                $scope.getUserGroup();
            }

        });
    };

    $scope.delCompanyAdmin = function (code) {
        companyService.delCompanyAdmin(code, function (d) {
            $scope.userList = [];
            $scope.getUserGroup();
        });
    }
    $scope.edit = function (data) {

        data.serviceType3_code = [];
        data.serviceType3_title = [];


        for (var i = 0; i < $scope.serviceListNew1.length; i++) {
            var list1 = $scope.serviceListNew1[i].child;
            for (var a = 0; a < $scope.serviceListNew1[i].child.length; a++) {
                var list2 = $scope.serviceListNew1[i].child[a].child;
                for (var b = 0; b < $scope.serviceListNew1[i].child[a].child.length; b++) {
                    if ($scope.serviceListNew1[i].child[a].child[b].chk != undefined &&
                        $scope.serviceListNew1[i].child[a].child[b].chk) {
                        data.serviceType3_code.push($scope.serviceListNew1[i].child[a].child[b].code);
                        data.serviceType3_title.push($scope.serviceListNew1[i].child[a].child[b].title);
                    }

                }
            }

        }
        companyService.add(data, $scope.app_id, function (json) {

            if (json.status) {
                var manager = JSON.parse(localStorage.getItem(sessionStorage.getItem("who") + "manager"));
                if (manager.company_code != undefined) {
                    $location.path('/grabPool');
                } else {
                    $location.path('/company/list');
                }
            }

        }, $scope.pageType);
    };

    $scope.$on('ngRepeatFinished', function (ngRepeatFinishedEvent) {
        init();
    });


}

function companyListController($scope, $routeParams, $window, $location, $http, companyService) {
    $scope.URL = WEB_URL;
    $scope.app_id = $routeParams.app_id;
    $scope.selectedPage = 1;
    $scope.data = {
        selectedPage: $scope.selectedPage
    };
    $scope.limit = 20;
    $scope.getList = function () {
        companyService.list($scope.limit, $scope.selectedPage, $scope.app_id, function (json) {
            $scope.list = json.list;
            $scope.count = json.count;
            $scope.currentPage = 1;
            $scope.getPage(json.count);
        });
    };
    $scope.getList();

    /*分页*/
    $scope.changePage = function (p) {
        $scope.data.selectedPage = p;
        companyService.list($scope.limit, p, $scope.app_id, function (json) {
            $scope.list = json.list;
            $scope.count = json.count;
            $scope.currentPage = p;
            $scope.getPage(json.count);
        });
    };
    $scope.getPage = function (count) {
        $scope.pageList = [];
        var limit = 20; //返回的条数
        $scope.totalPage = parseInt(count / limit); //总页数
        $scope.totalPage += count % limit >= 1 ? 1 : 0; //判断页数是否是整数
        var start = ($scope.currentPage - 2) >= 1 ? $scope.currentPage - 2 : 1; //首页
        var end = ($scope.currentPage + 2) <= $scope.totalPage ? $scope.currentPage + 2 : $scope.totalPage; //尾页

        $scope.frontdotShow = start > 1 ? true : false; //前面的省略号
        $scope.backdotShow = end < $scope.totalPage ? true : false; //后面的省略号
        for (var i = start; i <= end; i++) {
            $scope.pageList.push({
                number: i,
                active: i == $scope.currentPage ? 'active' : ''
            }); //给点击的按钮添加class
            console.log(count);
        }
    };


    $scope.delete = function (company) {

        companyService.delete(company.code, $scope.app_id, function (json) {

            if (json.status) {
                $scope.getList();
            }

        });

    }

}